import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入store
import store from '@/store'
import Login from '@/views/login'
import Register from '@/views/register'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home', // 默认显示首页的二级路由
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/ArticleCategory')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/ArticleList')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/UserInfo')
      }, {
        path: 'user-avatar',
        component: () => import('@/views/user/ChangePic')
      }, {
        path: 'user-pwd',
        component: () => import('@/views/user/ChangePassword')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 白名单
const whiteList = ['/login', '/register']
// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 如果有token, 直接放行
  const token = store.state.user.token
  if (token) {
    next()
    return
  }
  // 判断要跳转的页面在不在白名单内
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  // 其他情况则直接跳转到登录页
  next('/login')
})

export default router
